package cn.com.api.service.impl;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.api.entity.ApiCash;
import cn.com.api.entity.ApiShop;
import cn.com.api.entity.ApiShopTodayStats;
import cn.com.api.entity.ApiSmslog;
import cn.com.api.entity.ApiT_Cash;
import cn.com.api.entity.ApiT_shipping;
import cn.com.api.entity.ApiT_shops_pay_records;
import cn.com.api.entity.ApiT_token;
import cn.com.api.mapper.ApiCashMapper;
import cn.com.api.mapper.ApiDianPingMapper;
import cn.com.api.mapper.ApiDingDanMapper;
import cn.com.api.mapper.ApiGoodsMapper;
import cn.com.api.mapper.ApiShopsMapper;
import cn.com.api.mapper.ApiT_browse_historyMapper;
import cn.com.api.mapper.ApiT_logMapper;
import cn.com.api.mapper.ApiT_productsMapper;
import cn.com.api.mapper.ApiT_shippingMapper;
import cn.com.api.mapper.ApiT_shop_pay_recordsMapper;
import cn.com.api.mapper.ApiT_shops_applyMapper;
import cn.com.api.mapper.ApiT_statsMapper;
import cn.com.api.mapper.ApiT_tokenMapper;
import cn.com.api.resultpage.InitShopListPage;
import cn.com.api.service.ApiShopsService;
import cn.com.api.service.ApiShopsTimeService;
import cn.com.api.service.ApiTypeService;
import cn.com.api.service.StartOnLoadService;
import cn.com.util.DateUtil;
import cn.com.util.*;


@Service
public class ApiShopsServiceImpl implements ApiShopsService {
	@Autowired
	private StartOnLoadService startOnLoadService;
	@Autowired
	private ApiTypeService apiTypeService;
	@Autowired
	private ApiShopsMapper apiShopsMapper;
	@Autowired
	private ApiDingDanMapper dingDanMapper;
	@Autowired
	private ApiCashMapper cashMapper;
	@Autowired
	private ApiT_statsMapper statsMapper;
	@Autowired
	private ApiT_tokenMapper apiT_tokenMapper;
	@Autowired
	private ApiT_shippingMapper apiT_shippingMapper;
	@Autowired
	private ApiGoodsMapper apiGoodsMapper;
	@Autowired
	private ApiT_productsMapper apiT_productsMapper;
	@Autowired
	private ApiT_shops_applyMapper applyMapper;
	@Autowired
	private ApiT_shops_applyMapper apiT_shops_applyMapper;
	@Autowired
	private ApiDianPingMapper dianPingMapper;
	@Autowired
	private ApiT_shop_pay_recordsMapper apiT_shop_pay_recordsMapper;
	@Autowired
	private ApiShopsTimeService apiShopsTimeServiceImpl;
	@Autowired
	private ApiT_logMapper apiT_logMapper;
	@Autowired
	private ApiT_browse_historyMapper apiT_browse_historyMapper;

	/**
	 * 登录成功后返回一个新的token
	 */
	@Override
	public ApiShop login(ApiShop shop) {
		ApiShop apiShop = apiShopsMapper.login(shop.getcUname(), shop.getcPass());
		if (apiShop != null) {
			apiShop.setDeviceid(shop.getDeviceid());
			apiShop.setDevicetype(shop.getDevicetype());
			apiShop.setIs_login(1);
			if (apiShop.getIs_open() == -1) {
				apiShop.setIs_open(0);
			}
			apiShopsMapper.updateT_shops(apiShop);

			String token = Utils.getToken(shop.getcUname());
			// 根据u_id 和 role 查询token表 role=1商户
			ApiT_token apiTtoken = apiT_tokenMapper.selectApiT_tokenByUidAndRole(apiShop.getcId(), 1);
			if (apiTtoken != null) {
				apiTtoken.setToken(token);
				apiTtoken.setOperatedate(DateUtil.nowTimeToString());
				apiT_tokenMapper.updateT_token(apiTtoken);
			} else {
				apiTtoken = new ApiT_token();
				apiTtoken.setUserid(apiShop.getcId().toString());
				apiTtoken.setRole(1);
				apiTtoken.setToken(token);
				apiTtoken.setOperatedate(DateUtil.nowTimeToString());
				apiT_tokenMapper.insertT_token(apiTtoken);
			}
			apiShop.setToken(token);
		} // 否则用户名或密码错误
		return apiShop;
	}

	@Override
	public List<ApiShop> getShops(Integer sid) {
		List<ApiShop> shopList = apiShopsMapper.getShopsById(sid);
		if (shopList != null && shopList.size() > 0) {
			for (ApiShop shop : shopList) {
				// 店铺类型
				shop.setIsEdit(apiTypeService.getShopType(shop.getcType()));
				shop.setSumSoldCount(shop.getCount());
			}
		}
		return shopList;
	}

	// 查询我收藏的商店
	public List<ApiShop> searchMyShops(@Param("u_id") String u_id) {
		List<ApiShop> list = apiShopsMapper.searchMyShops(u_id);
		System.err.println(u_id);
		System.out.println(list);
		return list;
	}

	// 查询我收藏的商店
	public List<Map<String, Object>> searchMyShopsPage(String u_id, PageInfo page) {
		return apiT_logMapper.findT_logs4ShopsByUserIdListPage(u_id, page);
	}

	@Override
	public ApiShop findShopByCid(String cId) {
		ApiShop shop = apiShopsMapper.findShopByCid(cId);
		return shop;
	}

	@Override
	public ApiShop findShopByCmobi(String c_mobi) {
		ApiShop shop = apiShopsMapper.findShopByCmobi(c_mobi);
		return shop;
	}

	@Override
	public ApiShop forgetPwd(ApiShop shop, ApiSmslog apiSmslog) {
		// 更新用户信息-密码
		// apiCommonService.updateApiTmemberPass(member);
		// 更新验证码状态-已验证
		// apiSmslogService.updateSmslog(apiSmslog);
		// 更新用户token
		// apiCommonService.updateApiTmember(member);
		return null;
	}

	@Override
	public void searchShopsByType(Map<String, String> params, Map<String, Object> map) {
		Integer cType = Integer.valueOf(params.get("cType"));
		Integer c_city_id = Integer.valueOf(params.get("city_id"));
		Integer pageCount = Integer.valueOf(params.get("pageCount"));
		String longitude = params.get("longitude");
		String latitude = params.get("latitude");
		String searchBy = params.get("searchBy");

		PageInfo page = new PageInfo();
		page.setCurrentPage(pageCount);

		Map<String, Object> paramsData = new HashMap<String, Object>();
		paramsData.put("c_type", cType);
		paramsData.put("c_city_id", c_city_id);
		paramsData.put("longitude", longitude);
		paramsData.put("latitude", latitude);
		paramsData.put("searchBy", searchBy);

		List<ApiShop> shopList = new ArrayList<ApiShop>();
		shopList = apiShopsMapper.searchShopByConditionListPage(paramsData, page);
		if (shopList != null && shopList.size() > 0) {
			for (ApiShop shop : shopList) {
				// 距离
				Double to_user_distance = Utils.GetDistance(latitude, longitude, shop.getLatitude() + "",
						shop.getLongitude() + "");
				// System.out.println("to_user_distance:"+to_user_distance);
				shop.setTo_user_distance(to_user_distance);
				// 已售数量
				Integer sumSoldCount = apiT_productsMapper.getSumSoldCountByShopId(shop.getcId());
				if (sumSoldCount == null) {
					sumSoldCount = 0;
				}
				shop.setSumSoldCount(sumSoldCount);
				// 几星评价 score--平均评价
				Map<String, Object> paramsMap = new HashMap<String, Object>();
				paramsMap.put("shop_id", shop.getcId());

				List<Map<String, Object>> results = dianPingMapper.searchDianPingSumInfoByShopid(paramsMap);
				Integer allCount = 0;
				Integer sumScore = 0;
				if (results != null && results.size() > 0) {
					for (Map<String, Object> maps : results) {
						Integer grade = Integer.parseInt(maps.get("grade").toString());
						Integer count = Integer.parseInt(maps.get("count").toString());
						allCount = allCount + count;
						sumScore = sumScore + grade * count;
					}
				}
				Double score = 0.0;
				if (allCount != 0) {
					score = sumScore / (double) allCount;// 评分
					BigDecimal b = new BigDecimal(score);
					score = b.setScale(0, BigDecimal.ROUND_HALF_UP).doubleValue();
				}
				shop.setScore(score);
				if (shop.getIs_open() == 1) {
					if (!apiShopsTimeServiceImpl.checkNowDateInShopTime(shop.getcId())) {
						shop.setIs_open(0);
					}
				} else if (shop.getIs_open() == -1) {
					shop.setIs_open(0);
				}
			}
		}

		InitShopListPage initShopListPage = new InitShopListPage();
		initShopListPage.setShopList(shopList);
		initShopListPage.setPage(page);
		initShopListPage.setTotalPage(page.getTotalPage());
		map.put("datas", initShopListPage);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");

	}

	@Override
	public List<ApiShop> searchShopsByEnable(Integer cEnable) {
		return apiShopsMapper.searchShopsByEnable(cEnable);
	}

	// 根据id获取
	public ApiShop findT_shopsById(Integer c_id) {
		ApiShop t_shops = apiShopsMapper.findT_shopsById(c_id);
		return t_shops;
	}

	// 添加
	public int insertT_shops(ApiShop t_shops) {
		int ret_I = apiShopsMapper.insertT_shops(t_shops);
		return ret_I;
	}

	// 修改
	public int updateT_shops(ApiShop t_shops) {
		int ret_I = apiShopsMapper.updateT_shops(t_shops);
		return ret_I;
	}

	// 删除
	public int deleteT_shops(Integer c_id) {
		int ret_I = apiShopsMapper.deleteT_shops(c_id);
		return ret_I;
	}

	@Override
	public List<ApiShop> searchShopByCondition(Map<String, Object> map) {
		Integer pageCount = Integer.valueOf(map.get("pageCount").toString());
		PageInfo page = new PageInfo();
		page.setCurrentPage(pageCount);
		return apiShopsMapper.searchShopByConditionListPage(map, page);
	}

	@Override
	public List<ApiShop> findShops() {
		// TODO
		List<ApiShop> shopList = apiShopsMapper.findShops();
		return shopList;
	}

	@Override
	public int modifyPass_shops(ApiShop t_shops) {
		int ret_I = apiShopsMapper.modifyPass_shops(t_shops);
		return ret_I;
	}

	@Override
	public Integer searType(String shopid) {
		return null ; // shopsMapper.searType(shopid);
	}

	@Override
	public ApiShopTodayStats getShopOrderAccount(Integer shop_id) {
		// TODO
		ApiShopTodayStats stats = apiShopsMapper.getShopAccountToday(shop_id);
		return stats;
	}

	@Override
	public ApiShopTodayStats getShopOrderAccountDay(Integer shop_id, String day) {
		// TODO
		ApiShopTodayStats stats = apiShopsMapper.getShopAccountDay(shop_id, day);
		return stats;
	}

	@Override
	public boolean updateTel(String tel, String id) {
		return apiShopsMapper.updateTel(tel, id);
	}

	@Override
	public Map<String, Object> findShopByShopId(String shopid) {
		return apiShopsMapper.findShopByShopId(shopid);
	}

	public ApiShop searchShopsZiYingByCityId(String city_id) {
		return apiShopsMapper.searchShopsZiYingByCityId(city_id);
	}

	@Override
	@Transactional
	public boolean shopCash(ApiCash apiCash) {
		DecimalFormat df = new DecimalFormat("######0.00");
		Map<String, Object> shop = apiShopsMapper.findShopByShopId(apiCash.getShopid() + "");
		Double cashMoney = Double.parseDouble(df
				.format(Double.parseDouble(shop.get("cash_money") + "") - Double.parseDouble(apiCash.getMoney() + "")));
		apiShopsMapper.updateCashPre(cashMoney, Double.parseDouble(shop.get("pre_payment") + ""), apiCash.getShopid());
		return cashMapper.addShopCash(apiCash);
	}

	@Override
	public boolean updateCashPre(Double cmoney, Double payment, Integer id) {
		return apiShopsMapper.updateCashPre(cmoney, payment, id);
	}

	@Override
	public Map<String, Object> shopStat(String shopid) {
		Map<String, Object> res = new HashMap<String, Object>();
		try {
			SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
			Date date = new Date();
			Map<String, Object> stat = new HashMap<String, Object>();

			Double orderMoney = 0.00;
			Integer orderCount = 0;

			List<Map<String, Object>> perList = new ArrayList<Map<String, Object>>();// 下单
			perList = dingDanMapper.shopDayOrderPer(dateFormater.format(date), shopid);
			List<String> time = new ArrayList<String>();
			for (int i = 1; i < 8; i++) {
				Calendar calendar = Calendar.getInstance();
				calendar.setTime(date);
				calendar.add(Calendar.DATE, -i);
				time.add(dateFormater.format(calendar.getTime()));
			}

			List<ApiT_shipping> shippingList = apiT_shippingMapper.searchTodayFinishTask(dateFormater.format(date));

			if (shippingList != null && shippingList.size() > 0) {
				System.out.println("-----shippingList有值");
				// 2-按店铺
				Map<Integer, List<ApiT_shipping>> shopMap = new HashMap<Integer, List<ApiT_shipping>>();
				for (ApiT_shipping ship : shippingList) {
					Integer shop_id = ship.getShop_id();
					if (shopMap.containsKey(shop_id)) {
						shopMap.get(shop_id).add(ship);
					} else {
						List<ApiT_shipping> shopList = new ArrayList<ApiT_shipping>();
						shopList.add(ship);
						shopMap.put(shop_id, shopList);
					}
				}

				for (Entry<Integer, List<ApiT_shipping>> entry : shopMap.entrySet()) {
					List<ApiT_shipping> shipList = entry.getValue();
					// 遍历获取金额 订单总数量
					Double sumMoney = 0.0;
					Integer count = shipList.size();
					for (ApiT_shipping s : shipList) {
						sumMoney = sumMoney + s.getMoney().doubleValue();
					}
					orderMoney = sumMoney;
					orderCount = count;
				}
			}

			DecimalFormat df = new DecimalFormat("######0.00");
			Integer orderPerCount = perList.size();
			List<Map<String, Object>> week = new ArrayList<Map<String, Object>>();
			week = statsMapper.shopSevenStat(time, shopid);
			stat.put("orderMoney", orderMoney + "");// 订单总额
			stat.put("orderCount", orderCount + "");// 下单数
			stat.put("orderPerCount", orderPerCount + "");// 下单人数
			stat.put("visitPerCount", "123");// 访问人数
			stat.put("conversion", "30%");// 转化率
			stat.put("avgOrderMoney", orderCount == 0 ? orderCount : df.format(orderMoney / orderCount));// 平均订单额
			stat.put("avgPerMoney", orderPerCount == 0 ? orderPerCount : df.format(orderMoney / orderPerCount) + "");// 客单价
			stat.put("weekSource", week);
			res.put("datas", stat);
			res.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			res.put(Utils.MESSAGE, "查询成功");
		} catch (Exception e) {
			e.printStackTrace();
			res.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			res.put(Utils.MESSAGE, "系统异常");
		}
		return res;
	}

	// 获取（指定日期）报表明细
	public Map<String, Object> shopDateStat(String shopid, String date) {
		Map<String, Object> res = new HashMap<String, Object>();
		try {
			SimpleDateFormat dateFormater = new SimpleDateFormat("yyyy-MM-dd");
			Map<String, Object> stat = new HashMap<String, Object>();
			// 获取完成状态的订单数量和订单金额
			Map<String, Object> countAndMoneyResult = dingDanMapper.getorderCountAndSummoney(shopid, date);

			DecimalFormat df = new DecimalFormat("######0.00");
			Double orderMoney = 0.00;
			Integer orderCount = 0;
			if (countAndMoneyResult.get("count") != null) {
				orderCount = Integer.valueOf(countAndMoneyResult.get("count").toString());
			}
			if (countAndMoneyResult.get("money") != null) {
				orderMoney = Double.valueOf(countAndMoneyResult.get("money").toString());
			}
			// 下单人数
			Integer payPersonSum = dingDanMapper.getPayPersonSum(shopid, date);
			// 访问人数
			Integer sumBrowsePerson = apiT_browse_historyMapper.getSumBrowsePerson(shopid, date);

			stat.put("orderMoney", orderMoney);// 订单总额
			stat.put("orderCount", orderCount + "");// 下单数
			stat.put("orderPerCount", payPersonSum + "");// 下单人数
			stat.put("visitPerCount", sumBrowsePerson + "");// 访问人数

			// 创建一个数值格式化对象
			NumberFormat numberFormat = NumberFormat.getInstance();
			// 设置精确到小数点后2位
			numberFormat.setMaximumFractionDigits(2);
			stat.put("conversion", sumBrowsePerson == 0 ? sumBrowsePerson + "%"
					: numberFormat.format((float) payPersonSum / (float) sumBrowsePerson * 100) + "%");// 转化率

			stat.put("avgOrderMoney", orderCount == 0 ? orderCount : df.format(orderMoney / orderCount));// 平均订单额
			stat.put("avgPerMoney", payPersonSum == 0 ? payPersonSum : df.format(orderMoney / payPersonSum) + "");// 客单价
			res.put("datas", stat);
			res.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			res.put(Utils.MESSAGE, "查询成功");
		} catch (Exception e) {
			e.printStackTrace();
			res.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			res.put(Utils.MESSAGE, "系统异常");
		}
		return res;
	}

	@Override
	public Map<String, Object> shopBills(String shopid) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			List<Map<String, Object>> cash = new ArrayList<Map<String, Object>>();
			List<ApiT_shops_pay_records> record = new ArrayList<ApiT_shops_pay_records>();
			List<Map<String, Object>> stats = new ArrayList<Map<String, Object>>();
			List<Map<String, Object>> res = new ArrayList<Map<String, Object>>();
			Map<String, Object> shop = new HashMap<String, Object>();
			DecimalFormat df = new DecimalFormat("######0.00");
			shop = apiShopsMapper.findShopByShopId(shopid);
			record = apiT_shop_pay_recordsMapper.searAll(shopid);// 打款记录
			cash = cashMapper.searByShopId(shopid, "1");
			stats = statsMapper.statWeekByShopId(shopid);
			/*
			 * for (Map<String, Object> m : cash) { Map<String, Object> c = new
			 * HashMap<String, Object>(); c.put("title", "余额提现"); c.put("money",
			 * df.format(m.get("money"))); c.put("time",
			 * m.get("time").toString().split(" ")[0]); c.put("type", "0");
			 * c.put("id", m.get("id") + ""); c.put("balance",
			 * df.format(m.get("after_money"))); res.add(c); }
			 */
			for (ApiT_shops_pay_records pay : record) {
				Map<String, Object> c = new HashMap<String, Object>();
				if (pay.getType() == 1) {
					c.put("title", "周结打款");
				} else if (pay.getType() == 2) {
					c.put("title", "月结打款");
				} else if (pay.getType() == 3) {
					c.put("title", "余额提现");
				}
				c.put("money", df.format(pay.getMoney()));
				c.put("time", pay.getTime());
				c.put("type", "0");
				c.put("id", pay.getRecord_id());
				c.put("balance", pay.getAfter_money());
				res.add(c);
			}
			for (Map<String, Object> m : stats) {

				List<Map<String, Object>> stas = new ArrayList<Map<String, Object>>();
				stas = statsMapper.searByWeek(m.get("week") + "", shopid);
				Double sjmoney = 0.0;
				for (Map<String, Object> mp : stas) {
					String sid = mp.get("stats_id").toString();
					Map<String, Object> stat = new HashMap<String, Object>();
					stat = statsMapper.searById(sid);
					/*
					 * Double total =
					 * Double.parseDouble(stat.get("orders_money") + "");// 总价
					 * Double discount = Double.parseDouble(shop.get("discount")
					 * + "");// 折扣 Double sqdis =
					 * Double.parseDouble(stat.get("sendfee") + "");// 收取配送费
					 * Double sqfc = Double.parseDouble(df.format(total - (total
					 * - sqdis) * discount));// 商品分成
					 */
					Double sj = Double.parseDouble(df.format(stat.get("final_pay_money")));// 实际收入
					sjmoney += sj;
				}

				Map<String, Object> c = new HashMap<String, Object>();
				String stime = format.format(m.get("startTime"));
				String etime = format.format(m.get("endTime"));
				c.put("title", stime + "~" + etime + "日账单");
				c.put("money", df.format(sjmoney));
				c.put("time", etime);
				c.put("type", "1");
				c.put("id", m.get("week") + "");
				c.put("balance", df.format(m.get("balance")));
				res.add(c);
			}
			//Collections.sort(res, new ComparatorUtil());
			map.put("datas", res);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "查询成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常");
		}
		return map;
	}

	@Override
	public Map<String, Object> cashDetail(String cashid, String token) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			Map<String, Object> cash = new HashMap<String, Object>();
			/*
			 * cash = cashMapper.searCashById(cashid, "1"); cash.put("remark",
			 * "");
			 */
			cash = apiT_shop_pay_recordsMapper.searById(cashid);
			cash.put("remark", "");
			Integer type = Integer.parseInt(cash.get("type") + "");
			if (type == 1) {
				cash.put("balance", "周结打款");
			} else if (type == 2) {
				cash.put("balance", "月结打款");
			} else if (type == 3) {
				cash.put("balance", "余额提现");
			}
			map.put("datas", cash);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "查询成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常");
		}
		return map;
	}

	@Override
	public Map<String, Object> statDetail(String statid, String shopid, String token) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
			Map<String, Object> shop = new HashMap<String, Object>();
			shop = apiShopsMapper.findShopByShopId(shopid);
			List<Map<String, Object>> stats = new ArrayList<Map<String, Object>>();
			stats = statsMapper.searByWeek(statid, shopid);

			for (Map<String, Object> m : stats) {
				String sid = m.get("stats_id").toString();
				Map<String, Object> res = new HashMap<String, Object>();
				Map<String, Object> stat = new HashMap<String, Object>();
				stat = statsMapper.searById(sid);
				DecimalFormat df = new DecimalFormat("######0.00");
				// Double psf =
				// Double.parseDouble(StartOnLoadService.dictionaryMap.get("SENDFEE"));//系统配送费
				Integer countOrder = Integer.parseInt(stat.get("order_count") + "");// 总单数
				Double total = Double.parseDouble(stat.get("orders_money") + "");// 总价
				Double discount = Double.parseDouble(shop.get("discount") + "");// 折扣
				// Double sqdis=Double.parseDouble(df.format(countOrder *
				// psf));//收取配送费
				Double sqdis = Double.parseDouble(stat.get("sendfee") + "");// 收取配送费
				Double sqfc = Double.parseDouble(df.format(total - (total - sqdis) * discount));// 商品分成
				Double sj = Double.parseDouble(df.format(total - sqfc));// 实际收入
				res.put("time", stat.get("create_time"));// 日期
				res.put("countOrder", countOrder + "");// 总单数
				res.put("money", sj + "");// 实际收入
				res.put("payment", total + "");// 支付金额
				res.put("activity", "0.00");// 活动款
				res.put("deduct", sqfc + "");// 商品分成
				res.put("sendfee", sqdis + "");// 收取配送费
				list.add(res);
			}
			map.put("datas", list);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "查询成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常");
		}
		return map;
	}

	@Override
	public List<Map<String, Object>> searCashAll() {
		return cashMapper.searAll();
	}

	@Override
	@Transactional
	public int cashReview(String cashid, String type) {
		Map<String, Object> cash = new HashMap<String, Object>();
		cash = cashMapper.searCashInfo(cashid);
		DecimalFormat df = new DecimalFormat("######0.00");
		Double money = Double.parseDouble(df.format(cash.get("money")));
		if ("1".equals(type)) {// 审核通过
			ApiT_Cash newCash = new ApiT_Cash();
			newCash.setStatus(1);
			newCash.setId(Integer.parseInt(cashid));
			apiT_shops_applyMapper.updateCash(newCash);
		} else if ("2".equals(type)) {// 审核不通过
			ApiT_Cash newCash = new ApiT_Cash();
			newCash.setStatus(2);
			newCash.setId(Integer.parseInt(cashid));
			apiT_shops_applyMapper.updateCash(newCash);

			Map<String, Object> shop = new HashMap<String, Object>();
			String shopid = cash.get("shop_id") + "";
			shop = apiShopsMapper.findShopByShopId(shopid);
			Double cmoney = Double.parseDouble(df.format(shop.get("cash_money")));
			Double payment = Double.parseDouble(df.format(shop.get("pre_payment")));
			boolean two = apiShopsMapper.updateCashPre(Double.parseDouble(df.format(cmoney + money)), payment,
					Integer.parseInt(shopid));
			if (two) {
				return 1;
			}
			return 0;
		}
		return 0;
	}

	@Override
	public Map<String, Object> updateIsOpen(String open, String shopid) {
		Map<String, Object> map = new HashMap<String, Object>();
		try {
			apiShopsMapper.updateIsOpen(open, shopid);
			map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
			map.put(Utils.MESSAGE, "修改成功");
		} catch (Exception e) {
			e.printStackTrace();
			map.put(Utils.RESULT, Utils.RESULT_RC_EXCEPTION);
			map.put(Utils.MESSAGE, "系统异常");
		}
		return map;
	}

	@Override
	public List<ApiShop> searCondition(Map<String, Object> cond, PageInfo pageInfo) {
		return apiShopsMapper.searConditionListPage(cond, pageInfo);
	}

	@Override
	public List<ApiShop> searchShops(Map<String, Object> conditions) {
		return apiShopsMapper.searchShops(conditions);
	}

	@Override
	public void searchGoodsByShopId(Map<String, String> params, Map<String, Object> map) {
		String shop_id = params.get("shop_id");
		Integer pageCount = Integer.valueOf(params.get("pageCount"));

		PageInfo page = new PageInfo();
		page.setCurrentPage(pageCount);

		List<Map<String, String>> goodsList = apiGoodsMapper.searShopAllGoodsListPage(shop_id, page);

		InitShopListPage initShopListPage = new InitShopListPage();
		initShopListPage.setGoodsList(goodsList);
		initShopListPage.setPage(page);
		initShopListPage.setTotalPage(page.getTotalPage());
		map.put("datas", initShopListPage);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");

	}

	// 生活服务--附近的门店
	@Override
	public void searchNearbyShops(Map<String, String> params, Map<String, Object> map) {
		Integer city_id = Integer.valueOf(params.get("city_id"));
		Integer cCode = Integer.valueOf(params.get("cCode"));
		Integer pageCount = Integer.valueOf(params.get("pageCount"));
		String longitude = params.get("longitude");
		String latitude = params.get("latitude");

		PageInfo page = new PageInfo();
		page.setCurrentPage(pageCount);

		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("city_id", city_id);
		paramMap.put("cCode", cCode);
		paramMap.put("longitude", longitude);
		paramMap.put("latitude", latitude);

		List<ApiShop> shopList = apiShopsMapper.searchNearbyShopsListPage(paramMap, page);
		if (shopList != null && shopList.size() > 0) {
			for (ApiShop shop : shopList) {
				Integer sumSoldCount = apiT_productsMapper.getSumSoldCountByShopId(shop.getcId());
				if (sumSoldCount == null) {
					sumSoldCount = 0;
				}
				shop.setSumSoldCount(sumSoldCount);
			}
		}
		InitShopListPage initShopListPage = new InitShopListPage();
		initShopListPage.setShopList(shopList);
		initShopListPage.setPage(page);
		initShopListPage.setTotalPage(page.getTotalPage());
		map.put("datas", initShopListPage);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");
	}

	@Override
	public void searchShopsByShopName(Map<String, String> params, Map<String, Object> map) {
		String name = params.get("name");
		String city_id = params.get("city_id");
		String longitude = params.get("longitude");
		String latitude = params.get("latitude");
		Integer pageCount = Integer.valueOf(params.get("pageCount"));

		PageInfo page = new PageInfo();
		page.setCurrentPage(pageCount);

		List<ApiShop> shopList = apiShopsMapper.searchShopsByShopNameListPage(name, city_id, page);
		if (shopList != null && shopList.size() > 0) {
			for (ApiShop shop : shopList) {
				Double to_user_distance = Utils.GetDistance(latitude, longitude, shop.getLatitude() + "",
						shop.getLongitude() + "");
				shop.setTo_user_distance(to_user_distance);
				shop.setIsEdit(apiTypeService.getShopType(shop.getcType()));
				if (shop.getIs_open() == 1) {
					if (!apiShopsTimeServiceImpl.checkNowDateInShopTime(shop.getcId())) {
						shop.setIs_open(0);
					}
				} else if (shop.getIs_open() == -1) {
					shop.setIs_open(0);
				}
			}

		}
		InitShopListPage initShopListPage = new InitShopListPage();
		initShopListPage.setShopList(shopList);
		initShopListPage.setPage(page);
		initShopListPage.setTotalPage(page.getTotalPage());
		map.put("datas", initShopListPage);
		map.put(Utils.RESULT, Utils.RESULT_RC_SUCCESS);
		map.put(Utils.MESSAGE, "success");

	}

	@Override
	public Integer searByName(String name) {
		return apiShopsMapper.searByName(name);
	}

	@Override
	public List<ApiShop> findShopsAll() {
		return apiShopsMapper.findShopsAll();
	}

	@Override
	@Transactional
	public boolean updatePreMoney(String money, String shopId, ApiT_shops_pay_records payRecord, String applyid) {
		boolean result = apiShopsMapper.updatePreMoney(money, shopId);
		apiT_shops_applyMapper.updatePayMoney("1", applyid);

		String handle_time = DateUtil.nowTimeToString();

		ApiShop shop = apiShopsMapper.findT_shopsById(Integer.parseInt(shopId));
		Double cashMoney = shop.getCashMoney();// 商户余额
		// 添加打款记录
		// payRecord.setAfter_money(cashMoney);
		payRecord.setTime(handle_time);
		payRecord.setStats_id(Integer.parseInt(applyid));
		payRecord.setType(4);// 4：商家预付款申请打款
		payRecord.setShop_id(Integer.parseInt(shopId));
		payRecord.setNum(new Date().getTime() + shopId + "");
		apiT_shop_pay_recordsMapper.insertT_shop_pay_record(payRecord);

		return result;
	}

	@Override
	public List<Map<String, Object>> searShopCad(String sname) {
		return apiShopsMapper.searShopCad(sname);
	}

	@Override
	public Map<String, Object> searShopOrderDel(String shopid, String rid, String time, String stime, String etime) {
		List<Map<String, Object>> order = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> cash = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> apply = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> res = new ArrayList<Map<String, Object>>();
		Map<String, Object> result = new HashMap<String, Object>();
		Map<String, Object> price = new HashMap<String, Object>();
		// shop=apiShopsMapper.findShopByShopId(shopid);
		DecimalFormat df = new DecimalFormat("######0.00");
		// Double dis=Double.parseDouble(shop.get("discount")+"")*100;
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat day = new SimpleDateFormat("yyyy-MM-dd");
		SimpleDateFormat month = new SimpleDateFormat("yyyy-MM");
		Double ddje = 0.0;// 订单金额
		Double ddsr = 0.0;// 订单收入
		Double jkje = 0.0;// 结款金额
		if ((stime != null && !"".equals(stime)) || (etime != null && !"".equals(etime))) {
			time = null;
		} else {
			if ("day".equals(time)) {
				time = day.format(new Date());
			} else if ("month".equals(time)) {
				time = month.format(new Date());
			}
		}
		order = apiShopsMapper.searShopOrderDel(shopid, rid == null ? "" : rid, time == null ? "" : time,
				stime == null ? "" : stime, etime == null ? "" : etime);
		cash = cashMapper.searCashByShopId(shopid, rid == null ? "" : rid, time == null ? "" : time,
				stime == null ? "" : stime, etime == null ? "" : etime);
		apply = applyMapper.searByShopLog(shopid, time == null ? "" : time, stime == null ? "" : stime,
				etime == null ? "" : etime);
		for (Map<String, Object> mo : order) {
			Double discount = Double.parseDouble(mo.get("discount") + "");// 折扣
			Double sendfee = Double.parseDouble(mo.get("sendfee") + "");// 配送费
			Double money = Double.parseDouble(mo.get("money") + "");// 订单总额
			Double fg = Double.parseDouble(df.format((money - sendfee) * discount));
			mo.put("appdate", format.format(mo.get("appdate")));
			mo.put("arrive_user_time", format.format(mo.get("arrive_user_time")));
			mo.put("fc", df.format(money - sendfee - fg));// 商家分成
			mo.put("fg", fg);// 付给商家金额
			mo.put("type", "订单");
			mo.put("jk", "---");
			mo.put("discount", df.format((1 - discount) * 100));
			ddje += money;
			ddsr += fg;
			res.add(mo);
		}
		for (Map<String, Object> mc : cash) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("c_sname", mc.get("c_sname"));
			map.put("titles", mc.get("num"));
			map.put("money", "---");
			map.put("fc", "---");
			map.put("sendfee", "---");
			map.put("fg", "---");
			map.put("discount", "---");
			map.put("appdate", mc.get("time"));
			map.put("type", "提现");
			map.put("jk", mc.get("money"));
			jkje += Double.parseDouble(mc.get("money") + "");
			res.add(map);
		}
		for (Map<String, Object> mc : apply) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("c_sname", mc.get("c_sname"));
			map.put("titles", "---");
			map.put("money", "---");
			map.put("fc", "---");
			map.put("sendfee", "---");
			map.put("fg", "---");
			map.put("discount", "---");
			map.put("appdate", mc.get("create_time"));
			map.put("type", "预付充值");
			map.put("jk", mc.get("money"));
			jkje += Double.parseDouble(mc.get("money") + "");
			res.add(map);
		}
		price.put("ddje", df.format(ddje));
		price.put("ddsr", df.format(ddsr));
		price.put("jkje", df.format(ddsr));
		result.put("data", res);
		result.put("money", price);
		return result;
	}

	@Override
	public List<ApiShop> searchShopsByEnableAndCity(String cEnable, String cityid) {
		return apiShopsMapper.searchShopsByEnableAndCity(cEnable, cityid);
	}

	// 根据店铺id判断店铺是否是衣物干洗 1-是 0-否
	@Override
	public Integer checkShopIsClothes(Integer shop_id) {
		Integer flag = 0;
		String menu_yiwuganxi = startOnLoadService.dictionaryMap().get("menu_yiwuganxi".toUpperCase());
		// 查询该店铺的类型-根据shop_id
		ApiShop shop = apiShopsMapper.findT_shopsById(shop_id);
		if (shop != null) {
			String type = shop.getcType() + "";
			if (!Util.isNull(menu_yiwuganxi) && menu_yiwuganxi.equals(type)) {
				flag = 1;
			}
		}
		return flag;
	}

	// 店铺自动打烊或营业
	@Override
	public void autoIsOpen() {
		List<Map<String, Object>> shopAll = new ArrayList<Map<String, Object>>();
		shopAll = apiShopsMapper.searAllId();
		for (Map<String, Object> shop : shopAll) {
			if (!"0".equals(shop.get("is_open") + "")) {
				String shopid = shop.get("c_id") + "";
				if (apiShopsTimeServiceImpl.checkNowDateInShopTime(Integer.parseInt(shopid))) {
					apiShopsMapper.updateIsOpen("1", shopid);
				} else {
					apiShopsMapper.updateIsOpen("-1", shopid);
				}
			}
		}
	}

	public List<Map<String, Object>> getshopBillsListPage(Integer shop_id, PageInfo pageInfo) {
		return apiShopsMapper.getshopBillsListPage(shop_id, pageInfo);
	}
}
